<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class JAJobBoardModelJATax extends JModel
{
	
	var $_data;
	var $cate;
	var $_table;
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
		$this->cate =null;
	}
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}


	function &getItem()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__ja_tax '.
					'  WHERE id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();			
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->location_id = '';
			$this->_data->tax_value = '';
			$this->_data->published = '';			
		}
		return $this->_data;
	}
	
	function &getTable(){
		 if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_Tax', 'JobBoardTable');
		}
		return $this->_table;
	}
	// get all categories for parrent cat
	// save a category when edit or new.
	function store()	{		
		$db		 =& JFactory::getDBO();
		$post	= JRequest::get( 'post' );
				
		$row =& $this->getTable();
		
		$info = getItemByFieldName("ja_tax", "location_id", $post['location_id']);
		if($info && $post['id'] == "0"){			
			JError::raiseWarning ( 1, JText::_ ("Location has been taxed, please choose another"));
			return  false;
		}
		
		if (!$row->bind($post)) {
			$this->setError(JText::_("Invalid info"));
			return  false;
			
		}
		// Make sure the hello record is valid
		if (!$row->check()) {
			$this->setError(JText::_("Invalid info"));
			return false;
		}
		if (!$row->store()) 
		{
			$this->setError( JText::_("Invalid info") );
		}					
				
		return $row->id;
	}
	
	// Get unique code
	function getCode(){
	    $db =& JFactory::getDBO();
	    $code_length  = JRequest::getVar("code_length", "1");
	    $unique = $this->random_letters($code_length);        
        $query = "SELECT id FROM #__ja_coupon_code WHERE code = '".$unique."' ";
        $db->setQuery($query);
        $result = $db->loadResult();
        if( $result )
            return $this->getCode();
        else return $unique;
	}
	
	function random_letters ($numofletters) {
	    $vercode = "";
        if (!isset($numofletters)) 
            $numofletters = 10; // if $numofletters is not specified sets to 10 letters
        $literki = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'W', 'Z');
        $ilosc_literek = count($literki);
        for ($licz = 0; $licz < $numofletters; $licz++) {
            $rand = rand(0, $ilosc_literek-1);
            $vercode = $vercode.$literki[$rand];
        }
        return $vercode;
    } 
	
	// method delete one or more categories selected
	function delete()
	{
	    $db	=& JFactory::getDBO();
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		JArrayHelper::toInteger($cids, array(0));
		$row =& $this->getTable();
		if (count( $cids ))
		{
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );                    				
					return false;
				}
			}						
		}
		return true;
	}
	
	
	// method delete one or more categories selected
	function delete_code()
	{
	    $db	=& JFactory::getDBO();
		$id = JRequest::getVar( 'code_id', '0');
        $db->setQuery("DELETE FROM #__ja_coupon_code WHERE id = ".$id."");
        
        $result = $db->query();
        return $result;
    }
    
	function getcountcredit()
	{
		$db	=& JFactory::getDBO();
		$param = $this->getvar();
		$filter_order	= $param['filter_order'];
		$filter_order_Dir	= $param['filter_order_Dir']; 
		$search		= $param['search'];
		$search	= JString::strtolower( $search );
		$where = '  WHERE 1 ';
		$filter ='';
		if ($search) {
			$filter = ' AND LOWER(s.location_id) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
			}
		$query = 'SELECT COUNT(*)'
            	. ' FROM #__ja_coupon s'
            	;
		$query .=$where .$filter;
		$db->setQuery( $query );
		$total = $db->loadResult();
		return $total;
		
	}
	
	function getvar()
	{
		global $mainframe, $option;
		$list = array();
		$list['filter_order'] 		= JRequest::getVar('filter_order', 's.id');
		$list['filter_order_Dir'] 	= $mainframe->getUserStateFromRequest( $option.'.jacoupon.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$list['limit'] 		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$list['limitstart'] 	= $mainframe->getUserStateFromRequest( $option.'.jacoupon.limitstart', 'limitstart', 0, 'int' );
		$list['search'] 	= $mainframe->getUserStateFromRequest( $option.'.jacoupon.search',						'search',			'',				'string' );
		$list['option'] 	= $option;
		return  $list;
	}
	
	// get all subscriptions
	function getItems()
	{
		// Lets load the data if it doesn't already exist
		$db	=& JFactory::getDBO();
		$param = $this->getvar();
		$filter_order	= $param['filter_order'];
		$filter_order_Dir	= $param['filter_order_Dir']; 
		$limit		= $param['limit'];
		$limitstart	= $param['limitstart']; 
		$search		= $param['search'];
		$search	= JString::strtolower( $search );
		$filter ='';
		if ($search) {
			$filter = ' WHERE LOWER(s.location_id) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}
		$total = $this->getcountcredit();
		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );
		$order 			= ' ORDER BY  '. $filter_order .' '. $filter_order_Dir ;
		$query = 'SELECT  s.*, a.name FROM #__ja_tax AS s INNER JOIN #__ja_location as a ON a.id = s.location_id '
				.$filter. $order
				;
		
		$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
		$rows = $db->loadObjectList();
		for ($i=0;$i<count($rows);$i++)
			if (isset($rows[$i]->title))
			{
				$rows[$i]->title = JFilterInput::_decode($rows[$i]->title);
				$rows[$i]->title = JFilterInput::clean($rows[$i]->title);
			}
		return $rows;
	}
	
	// published categories
	function dopublish( $publish =1, $field='published')
	{
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());
		JArrayHelper::toInteger($cid, array(0));
		$ids = implode( ',', $ids );
		
		$query = "UPDATE #__ja_tax"
		. "\n SET $field = " . intval( $publish )
		. "\n WHERE id IN ( $ids )"
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}
	
	function getLocationTree($control_name="location_id", $values=null)
	{
	    $db =& JFactory::getDBO();
				
		$object_name = $control_name;
		$result = '<select name="'.$object_name .'">';
		$salary_checked = '';
		if (!is_array($values))
			$values = explode(',',$values);
		
	    $query = "SELECT * FROM #__ja_location where published = 1";
		$db->setQuery ( $query );
		$objects = $db->loadObjectList ();
		
		$objectHTML = array ();
		$children = array ();
		if ($objects) {
			foreach ( $objects as $v ) {
				$pt = $v->parent_id;
				$list = @$children [$pt] ? $children [$pt] : array ();
				array_push ( $list, $v );
				$children [$pt] = $list;
			}
			if (is_array ( $children )) {
				
				foreach ( $children as $key => $value ) {
					$temp = array ();
					$tmp_children = array ();
					if (is_array ( $children [$key] )) {
						foreach ( $children [$key] as $k => $v )
							$temp [$k] = $v->name;
						asort ( $temp );
						foreach ( $temp as $k => $v )
							$tmp_children [$k] = $children [$key] [$k];
						$children [$key] = $tmp_children;
					}
				}
			
			}
			
			$list = $this->treerecurse ( 0, '', array (), $children );
			if ($list) {
				foreach ( $list as $i => $item ) {
					$treename = $item->treename;
					$treename = JFilterOutput::ampReplace ( $treename );
					$treename = str_replace ( '"', '&quot;', $treename );
					if ($item->id == 0)
						$list [$i]->treename = $treename;
					else
						$list [$i]->treename = $treename;
				}
			}
			$objects = $list;
		}
		if (is_array($objects))
		foreach ( $objects as $key => $v ) {
			$objectHTML [] = JHTML::_ ( 'select.option', $key, $v->treename );
		}
		
		$strReturn = JHTML::_('select.genericlist',   $objectHTML, $object_name .'', 'class="inputbox" size="1"', 'value', 'text', $values);
		
		return $strReturn;
	}
	
	function treerecurse($id, $indent, $list, &$children, $maxlevel = 9999, $level = 0, $type = 1) {
    	if (@$children [$id] && $level <= $maxlevel) {
    		if (is_array ( $children ))
    			foreach ( $children [$id] as $v ) {
    				$id = $v->id;
    				
    				if ($type) {
    					$pre = '<sup>|_</sup>&nbsp;';
    					$spacer = '.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    				} else {
    					$pre = '- ';
    					$spacer = '&nbsp;&nbsp;';
    				}
    				
    				if ($v->parent_id == 0) {
    					$txt = $v->name;
    				} else {
    					$txt = $pre . $v->name;
    				}
    				$pt = $v->parent_id;
    				$list [$id] = $v;
    				$list [$id]->treename = "$indent$txt";
    				$list [$id]->children = count ( @$children [$id] );
    				$list = $this->treerecurse ( $id, $indent . $spacer, $list, $children, $maxlevel, $level + 1, $type );
    			}
    	}
    	
    	return $list;
    }
}
